import React, { useRef, useState } from "react";
// import mui
import {
  Paper,
  MenuList,
  MenuItem,
  ClickAwayListener,
  Grow,
  Popper,
  Typography,
} from "@mui/material";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
import { RowFlexBoxSC } from "../common/Common";
const OPTIONS = ["标题", "全文"];

export default function SelectMenu({ selectedIndex, setSelectedIndex }) {
  //控制下拉菜单的展开
  const [open, setOpen] = useState(false);
  const anchorRef = useRef(null);
  const handleMenuItemClick = (event, index) => {
    setSelectedIndex(index);
    console.log(index);
    setOpen(false);
  };
  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen);
  };

  const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return;
    }
    setOpen(false);
  };
  return (
    <RowFlexBoxSC
      sx={{
        width: "50px",
        height: "50px",
      }}
      ref={anchorRef} // 确保 RowFlexBoxSC 有 ref 引用
    >
      <RowFlexBoxSC
        sx={{ cursor: "pointer", display: "flex", alignItems: "center" }}
        onClick={handleToggle}
      >
        <Typography variant="body1 " noWrap sx={{ ml: 2, minWidth: "35px" }}>
          {OPTIONS[selectedIndex]}
        </Typography>
        <ArrowDropDownIcon sx={{ zIndex: 1 }} />
      </RowFlexBoxSC>

      <div>
        <Popper
          open={open}
          anchorEl={anchorRef.current} // 使用 RowFlexBoxSC 的 ref 作为 anchorEl
          placement="bottom" // 设置 Popper 在底部
          transition
          disablePortal
          modifiers={[
            {
              name: "offset",
              options: {
                offset: [20, -3], // [x, y] 偏移量，第一个值向右偏移，第二个值是垂直方向的偏移
              },
            },
          ]}
        >
          {({ TransitionProps }) => (
            <Grow {...TransitionProps}>
              <Paper>
                <ClickAwayListener onClickAway={handleClose}>
                  <MenuList id="split-button-menu" autoFocusItem sx={{width: "73px"}}>
                    {OPTIONS.map((option, index) => (
                      <MenuItem
                        key={option}
                        selected={index === selectedIndex}
                        onClick={(event) => handleMenuItemClick(event, index)}
                      >
                        <Typography variant="body1">{option}</Typography>
                      </MenuItem>
                    ))}
                  </MenuList>
                </ClickAwayListener>
              </Paper>
            </Grow>
          )}
        </Popper>
      </div>
    </RowFlexBoxSC>
  );
}
